package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class TokenInterceptorCheckToken implements HandlerInterceptor {

    @Autowired
    private JwtProperties props;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从请求头中获取token
        AppInfo info = null;
        try {
            String token = request.getHeader(props.getApp().getHeaderName());

            //使用公钥解析token
            Payload<AppInfo> infoFromToken = JwtUtils.getInfoFromToken(token, props.getPublicKey(), AppInfo.class);

            info = infoFromToken.getInfo();
        } catch (Exception e) {
            response.setStatus(403);
            return false;//不响应
        }

        //查验来的服务的目标id是否包含了当前服务id
        if (!info.getTargetList().contains(props.getApp().getId())){

            //没有token，或者token解析失败，或者不匹配则禁止访问
            response.setStatus(403);
            //不包含就要拦截，拦截就是不响应
            return false;
        }

       return true;
    }
}
